#include "addwork.h"
#include "ui_addwork.h"

addWork::addWork(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::addWork)
{
    ui->setupUi(this);

}

addWork::~addWork()
{
    delete ui;
}

//清空输入框
void addWork::on_retext_clicked()
{
    ui->pidEdit->clear();
    ui->priorityEdit->clear();
    ui->runtimeEdit->clear();
}

//提交新添加的进程，并将它插入数据库

void addWork::on_submit_clicked()
{
    QString pid = ui->pidEdit->text();
    QString priority = ui->priorityEdit->text();
    QString runtime = ui->runtimeEdit->text();
    QString memory = ui->memoryEdit->text();

    if(QString::compare(pid,"")!=0 && QString::compare(priority,"")!=0 && QString::compare(runtime,"") != 0 && QString::compare(memory,"") != 0)
    {
        bool priorityok, runtok, memok = false;
        int pri = priority.toInt(&priorityok);
        int runt = runtime.toInt(&runtok);
        int mem = memory.toInt(&memok);

        if(priorityok && runtok && memok)
        {
            PCB * p = new PCB(pid, pri, runt, mem);
            emit sendData(p);
            QMessageBox::information(nullptr, "add successfully", "添加成功");
            ui->pidEdit->clear();
            ui->priorityEdit->clear();
            ui->runtimeEdit->clear();
            ui->memoryEdit->clear();
//            QSqlDatabase db;
//            if(QSqlDatabase::contains("addworks"))
//            {
//                db = QSqlDatabase::database("addworks");
//            }
//            else{
//                db = QSqlDatabase::addDatabase("QMYSQL", "addworks");
//            }

//            db.setHostName("127.0.0.1");
//            db.setPort(3306);
//            db.setDatabaseName("cpuschedule");
//            db.setUserName("root");
//            db.setPassword("123456");

//            bool ok = db.open();

//            if(ok){
//                QString sql = QString("INSERT INTO backupque(pid, priority, runtime, status"
//                                      " VALUES('%1', %2, %3, 0").arg(pid).arg(pri).arg(runt);
//                QSqlQuery insert(db);
//                bool success = insert.exec(sql);

//                if(success)
//                {
//                    QMessageBox::information(nullptr, "database connect sucess", "添加成功");
//                }
//                else{
//                    QMessageBox::information(nullptr, "database connect error", "添加失败");
//                    QSqlError error;
//                    error=db.lastError();
//                    qDebug() << error;
//            }
        }
        else{
            QMessageBox::warning(nullptr, "please retext", "优先权级或运行时间必须为整数");
        }
    }
    else{
        QMessageBox::warning(nullptr, "please", "输入的信息不可为空");
        return;
    }
}
